package com.qsmx.store.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.databinding.DelegateApkManagerBinding;
import com.qsmx.store.core.fusion.FusionPre;
import com.qsmx.store.app.main.adapter.ApkListAdapter;
import com.qsmx.store.app.main.adapter.AppTypeSpanAdapter;
import com.qsmx.store.app.main.entity.AppInfoEntity;
import com.qsmx.store.app.main.entity.AppTypeEntity;
import com.qsmx.store.app.util.ApkManager;
import com.qsmx.store.app.util.DialogUtil;
import com.qsmx.store.app.util.DownloadUtil;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.net.HttpHelper;
import com.qsmx.store.core.net.HttpUrl;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;
import com.qsmx.store.core.util.StringUtil;
import com.qsmx.store.core.util.storage.AtmosPreference;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ApkManagerDelegate extends AtmosDelegate {

    private ApkListAdapter mAdapter;
    private List<AppTypeEntity.DataBean.AppTypeInfoListBean> mAppTypeList;
    private List<String> mAppTypeStringList;
    private List<AppInfoEntity.DataBean.VersionInfoListBean> mAppInfoList;
    private DelegateApkManagerBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_apk_manager;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBinding = DelegateApkManagerBinding.bind(rootView);
        mBinding.tvAppInfo.setText(Html.fromHtml(String.format(getString(R.string.app_info), AtmosPreference.getCustomStringPre(FusionPre.APP_ELM_INFO), ApkManager.getVersionName(getContext()))));

        mAppTypeStringList = new ArrayList<>();
        mAdapter = new ApkListAdapter(getContext());
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mBinding.rlvApkList.setAdapter(mAdapter);
        mBinding.rlvApkList.setLayoutManager(manager);
        getAppTypeList();

        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSupportDelegate().pop();
            }
        });

        mAdapter.setonItemClickListener(new ApkListAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                DialogUtil.showTwoButtonDialog(requireContext(), "是否下载" + mAppInfoList.get(position).getAppName() + "版本号：" + mAppInfoList.get(position).getVersionNo(), "取消", "确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtil.dismissTwoBtnDialog();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtil.dismissTwoBtnDialog();
                        downloadFile(mAppInfoList.get(position).getDownloadUrl(), mAppInfoList.get(position).getVersionNo(), mAppInfoList.get(position).getAppName());
                    }
                });
            }
        });
    }

    private void getAppTypeList() {

        HttpHelper.RestClientPost(new WeakHashMap<>(), HttpUrl.QUERY_APP_TYPE_LIST, new ISuccess() {
            @Override
            public void onSuccess(int code, String response) {
                Type type = new TypeToken<AppTypeEntity>() {
                }.getType();
                Gson gson = new Gson();
                AppTypeEntity mData = gson.fromJson(response, type);
                if (mData.getCode().equals("1")) {
                    mAppTypeList = mData.getData().getAppTypeInfoList();
                    mAppTypeStringList.clear();
                    for (AppTypeEntity.DataBean.AppTypeInfoListBean data : mData.getData().getAppTypeInfoList()) {
                        mAppTypeStringList.add(data.getAppName());
                    }
                    mAppTypeStringList.add("请选择项目");
                    initProjectSpanInfo();
                } else {
                    DialogUtil.showErrorDialog(getContext(), mData.getMessage(), "确定");
                }
            }
        }, new IError() {
            @Override
            public void onError(int code, String msg) {
                DialogUtil.showErrorDialog(getContext(), msg, "确定");
            }
        }, new IFailure() {
            @Override
            public void onFailure() {
                DialogUtil.showErrorDialog(getContext(), getString(R.string.un_know_error), "确定");
            }
        });
    }

    private void getAppInfo() {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("appType", mAppTypeList.get(mBinding.spAppType.getSelectedItemPosition()).getAppType());
        params.put("pageNum", "1");
        params.put("pageSize", "100");

        HttpHelper.RestClientPost(params, HttpUrl.QUERY_APP_LIST, new ISuccess() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onSuccess(int code, String response) {
                Type type = new TypeToken<AppInfoEntity>() {
                }.getType();
                Gson gson = new Gson();
                AppInfoEntity mData = gson.fromJson(response, type);
                if (mData.getCode().equals("1")) {
                    mAppInfoList = mData.getData().getVersionInfoList();
                    mAdapter.setData(mAppInfoList);
                    mAdapter.notifyDataSetChanged();
                } else {
                    DialogUtil.showErrorDialog(getContext(), mData.getMessage(), "确定");
                }
            }
        }, new IError() {
            @Override
            public void onError(int code, String msg) {
                DialogUtil.showErrorDialog(getContext(), msg, "确定");
            }
        }, new IFailure() {
            @Override
            public void onFailure() {
                DialogUtil.showErrorDialog(getContext(), getString(R.string.un_know_error), "确定");
            }
        });
    }

    private void initProjectSpanInfo() {

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mAppTypeStringList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBinding.spAppType.setAdapter(arrAdapter);
        mBinding.spAppType.setSelection(mAppTypeStringList.size() - 1, true);
        mBinding.spAppType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == mAppTypeStringList.size() - 1) {
                    return;
                }
                getAppInfo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void downloadFile(String downLoadUrl, String version, String appName) {
        ApkManagerDelegatePermissionsDispatcher.startCheckUpdateWithCheck(ApkManagerDelegate.this, downLoadUrl, version, appName);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startCheckUpdate(String url, String version, String appName) {
        DownloadUtil.DownLoadFile(requireContext(), url, version + "-" + StringUtil.getDateByTimestampNum(System.currentTimeMillis()), appName, url.split("\\.")[url.split("\\.").length - 1]);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileRational(PermissionRequest request) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ApkManagerDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
